<?php
namespace YDCMS\core;

class Router
{
    /**
     * @var array 路由规则
     */
    private $routes = [];
    private $notFoundCallback;
    private $middleware = [];

    /**
     * 解析路由
     * @return array
     */
    public function parse()
    {
        $uri = $this->getRequestUri();
        $method = $_SERVER['REQUEST_METHOD'];
        
        // 默认路由
        if (empty($uri) || $uri === '/') {
            return [
                'controller' => 'Home',
                'action' => 'index',
                'params' => []
            ];
        }
        
        // 解析URI
        $segments = explode('/', trim($uri, '/'));
        
        // 获取控制器
        $controller = ucfirst($segments[0] ?? 'Home');
        
        // 获取方法
        $action = $segments[1] ?? 'index';
        
        // 获取参数
        $params = array_slice($segments, 2);
        
        return [
            'controller' => $controller,
            'action' => $action,
            'params' => $params
        ];
    }

    /**
     * 获取请求URI
     * @return string
     */
    protected function getRequestUri()
    {
        $uri = $_SERVER['REQUEST_URI'];
        
        // 移除查询字符串
        if (false !== $pos = strpos($uri, '?')) {
            $uri = substr($uri, 0, $pos);
        }
        
        return $uri;
    }

    /**
     * 添加路由规则
     * @param string $pattern 路由模式
     * @param array $route 路由信息
     */
    public function addRoute($pattern, $route)
    {
        $this->routes[$pattern] = $route;
    }

    public function get($path, $callback, $middleware = [])
    {
        $this->routes['GET'][$path] = [
            'callback' => $callback,
            'middleware' => $middleware
        ];
    }

    public function post($path, $callback, $middleware = [])
    {
        $this->routes['POST'][$path] = [
            'callback' => $callback,
            'middleware' => $middleware
        ];
    }

    public function notFound($callback)
    {
        $this->notFoundCallback = $callback;
    }

    public function dispatch()
    {
        $method = $_SERVER['REQUEST_METHOD'];
        $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        
        // 移除尾部斜杠
        $path = rtrim($path, '/');
        if (empty($path)) {
            $path = '/';
        }

        if (isset($this->routes[$method][$path])) {
            $route = $this->routes[$method][$path];
            
            // Handle middleware
            if (isset($route['middleware'])) {
                foreach ($route['middleware'] as $middleware) {
                    $instance = new $middleware();
                    $instance->handle();
                }
            }
            
            $callback = $route['callback'];
            
            if (is_callable($callback)) {
                return call_user_func($callback);
            }
            
            if (is_array($callback)) {
                [$controller, $action] = $callback;
                $controller = new $controller();
                return $controller->$action();
            }
        }

        if ($this->notFoundCallback) {
            return call_user_func($this->notFoundCallback);
        }

        header("HTTP/1.0 404 Not Found");
        echo '404 Not Found';
    }
} 